package com.cert.test.dao;

import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.QueryRewriteContext;
import org.elasticsearch.index.query.QueryShardContext;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortFieldAndFormat;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * User: zsl
 * Date: 2020年7月15日, 0015
 * Time: 10:55
 * description:
 */
@Repository
public class EsQueryDaoImpl implements EsQueryDao {


    public static String INDEX_TEST = "index_test";
    public static String TYPE_TEST = "type_test";
    //    public static List<Tests> testsList = null;
    public static Long longId  = 99L;

    @Autowired
    private RestHighLevelClient client;

    /**
     * 使用QueryBuilder
     * termQuery("key", obj) 完全匹配 相当与 =
     * termsQuery("key", obj1, obj2..)   一次匹配多个值 相当与 = = =
     * matchQuery("key", Obj) 单个匹配, field不支持通配符, 前缀具高级特性    分词匹配
     * multiMatchQuery("text", "field1", "field2"..);  匹配多个字段, field有通配符忒行 多个分词匹配
     * matchAllQuery();         匹配所有文件  不带查询条件
     */

    @Override
    public void matchAllQuery() {

        SearchRequest searchRequest = new SearchRequest(INDEX_TEST);
        searchRequest.types(TYPE_TEST);
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(QueryBuilders.matchAllQuery()); // 添加 match_all 查询
        searchSourceBuilder.from(0); // 起始 index
        searchSourceBuilder.size(5); // 大小 size
        searchRequest.source(searchSourceBuilder); // 将 SearchSourceBuilder  添加到 SeachRequest 中
        try {
            SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
            SearchHits hits = response.getHits();
            long totalHits = hits.getTotalHits();
            float maxScore = hits.getMaxScore();
            System.out.println(totalHits+"<---->"+maxScore);
            hits.forEach( hit -> {
                Map<String, Object> sourceAsMap = hit.getSourceAsMap();
                System.out.println(sourceAsMap);
                System.out.println(sourceAsMap.get("name"));
                System.out.println(sourceAsMap.get("id"));
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 使用QueryBuilder
     * termQuery("key", obj) 完全匹配
     * termsQuery("key", obj1, obj2..)   一次匹配多个值
     * matchQuery("key", Obj) 单个匹配, field不支持通配符, 前缀具高级特性
     * multiMatchQuery("text", "field1", "field2"..);  匹配多个字段, field有通配符忒行
     * matchAllQuery();         匹配所有文件
     */

    @Override
    public void termQuery() {

        //基本查询
        SearchRequest searchRequest = new SearchRequest(INDEX_TEST);
        searchRequest.types(TYPE_TEST);
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.query(QueryBuilders.termQuery("name", "this is the one")); // 设置搜索，可以是任何类型的 QueryBuilder
        //分页
        sourceBuilder.from(0); // 起始 index
        sourceBuilder.size(7); // 大小 size
        sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS)); // 设置搜索的超时时间

        //排序
        SortBuilder sortBuilder = SortBuilders.fieldSort("id").order(SortOrder.ASC);
        sourceBuilder.sort(sortBuilder);
        searchRequest.source(sourceBuilder);
        try {
            SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
            SearchHits hits = response.getHits();
            long totalHits = hits.getTotalHits();
            float maxScore = hits.getMaxScore();
            System.out.println(totalHits+"<---->"+maxScore);
            hits.forEach( hit -> {
                Map<String, Object> sourceAsMap = hit.getSourceAsMap();
                System.out.println(sourceAsMap);
                System.out.println(sourceAsMap.get("name"));
                System.out.println(sourceAsMap.get("id"));
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    @Override
    public void matchQuery() {

        //基本查询
        SearchRequest searchRequest = new SearchRequest(INDEX_TEST);
        searchRequest.types(TYPE_TEST);
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.query(QueryBuilders.matchQuery("name", "this is the one")); // 设置搜索，可以是任何类型的 QueryBuilder
        sourceBuilder.from(0); // 起始 index
        sourceBuilder.size(10); // 大小 size
        sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS)); // 设置搜索的超时时间
        searchRequest.source(sourceBuilder);

        //排序
        SortBuilder sortBuilder = SortBuilders.fieldSort("id").order(SortOrder.ASC);
        sourceBuilder.sort(sortBuilder);
        searchRequest.source(sourceBuilder);


        try {
            SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
            SearchHits hits = response.getHits();
            long totalHits = hits.getTotalHits();
            float maxScore = hits.getMaxScore();
            System.out.println(totalHits+"<---->"+maxScore);
            hits.forEach( hit -> {
                Map<String, Object> sourceAsMap = hit.getSourceAsMap();
                System.out.println(sourceAsMap);
                System.out.println(sourceAsMap.get("name"));
                System.out.println(sourceAsMap.get("id"));
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
